package com.tedu.homework;

public class TestSynchronized {
    public static void main(String[] args) {
        Product p = new Product();
        boolean flag = false;
        Provider provider = new Provider(p,flag);
        Thread provider1 = new Thread(provider, "provider");
        consumer consumer = new consumer(p,flag);
        Thread consumer1 = new Thread(consumer, "consumer");


        provider1.start();
        consumer1.start();

    }
}
class Product{
    private String band;
    private String name;
    public Product(){}


    public String getBand() {
        return band;
    }

    public void setBand(String band) {
        this.band = band;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
class Provider implements Runnable{
    private Product product;
    boolean flag;

    public Provider(Product product,boolean flag) {
        this.product = product;
        this.flag = flag;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            synchronized (product) {
                if ( flag == false ){
                    product.setBand("哈尔滨");
                    product.setName("啤酒");
                    System.out.println(Thread.currentThread().getName()+"生产了"+product.getBand()+product.getName());
                    flag = true;
                    try {
                        product.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    this.notifyAll();
                }
            }
        }
    }
}
class consumer implements Runnable{
    private Product product;
    boolean flag;
    public consumer(Product product,boolean flag) {
        this.product = product;
        this.flag = flag;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }
    @Override
    public void run() {

        for (int i = 0; i < 10; i++) {
            synchronized (product){
                if (flag==false){
                    try {
                        product.wait();
                        flag = true;

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    System.out.println(Thread.currentThread().getName()+"消费品牌是"+product.getBand()+"名字是"+product.getName()+"产品");
                    flag = false;
                    product.notifyAll();
                }

            }
        }


    }
}
